package com.zhz.mutil.infras.utils;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常处理
 * @author zhouhengzhe
 */
@Slf4j
public class ExceptionUtils {
    private static String PROJECT_PACKAGE = "";

    public static void initProjectPackage() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        ArrayList<StackTraceElement> list = CollUtil.toList(stackTraceElements);
        for (StackTraceElement element : list) {
            if ("main".equals(element.getMethodName())) {
                PROJECT_PACKAGE = element.getClassName().substring(0, element.getClassName().lastIndexOf("."));
                break;
            }
        }
        log.info("PROJECT_PACKAGE: {}", PROJECT_PACKAGE);
    }

    public static String getProjectStackTrace(Throwable e) {
        Throwable cause=null;
        if (e.getCause()!=null){
            cause = e.getCause();
        }
        ArrayList<StackTraceElement> stackTraceElements = CollUtil.toList(e.getStackTrace());
        List<String> result = new ArrayList<>();
        for (StackTraceElement s : stackTraceElements) {
            String fileName = s.getClassName();
            int lineNumber = s.getLineNumber();
            // 忽略条件
            if (lineNumber == -1) {
                continue;
            }
            if (s.getClassName().startsWith(PROJECT_PACKAGE) || s.getClassName().startsWith("com.changzhi")) {
                result.add(fileName + "(" + lineNumber + ")");
            }
        }
        return "\n"+cause+"\n"+String.join("\n", result);
    }
}
